package cn.com.fssg.platform.base.handler.impl.cl.fuju;

import cn.com.fssg.platform.base.handler.InterfaceHandler;
import cn.com.fssg.platform.biz.BizUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;


@Component
public class ClFujuTypeHandler implements InterfaceHandler {
//    private NamedParameterJdbcTemplate jdbcTemplate = BizUtil.cur().tenantMainJdbcTemplate();
    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;
    private SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object run(HttpServletRequest request, JSONObject jsonObject) throws Exception {
        String type = jsonObject.getString("type");
        if(StringUtils.equals(type, "0")){
            //详情查询
            StringBuffer sql = new StringBuffer();
            sql.append("SELECT * FROM cl_huju_type");
            Map<String,Object>  map = new HashMap<>();
            Map<String,Object>  reultMap = new HashMap<>();
            if(StringUtils.isNotBlank(jsonObject.getString("id"))){
                sql.append(" WHERE id =:id");
                map.put("id",jsonObject.getString("id"));
                reultMap = jdbcTemplate.queryForMap(sql.toString(),map);
            }
            return reultMap;

        }else if(StringUtils.equals(type, "1")){
            Map<String,Object>  reultMap = new HashMap<>();
            StringBuffer sql = new StringBuffer();
            sql.append("SELECT * FROM cl_huju_type");
            Map<String,Object>  queryMap = new HashMap<>();
            sql.append(" WHERE id =:id");
            queryMap.put("id",jsonObject.getString("parent_id"));
            reultMap = jdbcTemplate.queryForMap(sql.toString(),queryMap);

            //添加
            Map<String,Object> map = new HashMap<>();
            //护具分类名称
            map.put("canji_type_name",jsonObject.getString("canji_type_name"));
            //父级id
            map.put("parent_id",jsonObject.getString("parent_id"));
            //护具分类规则
            map.put("rule",jsonObject.getString("rule"));
            //排序
            map.put("sort",jsonObject.getLong("sort"));
            //节点深度
            map.put("deep",Integer.valueOf(reultMap.get("deep").toString())+1);
            //祖父级节点
            map.put("parent_ids",jsonObject.getString("parent_ids"));

            //祖父级节点
            map.put("del_flag","0");

            if(StringUtils.isNotBlank(jsonObject.getString("id"))){
                //修改
                map.put("id",jsonObject.getString("id"));
                //修改时间
                map.put("update_time",new Date());
                //修改人
                //map.put("update_by","1");
                map.put("update_by",BizUtil.cur().curUserId());
                updateDatabase(map,"cl_huju_type");
            }else{
                //添加
                String id = BizUtil.cur().getSnowflakeIdStr();
                //String id = "12345";
                //ID
                map.put("id",id);
                //创建时间
                map.put("create_time",new Date());
                //创建人
                //map.put("create_by","1");
                map.put("create_by",BizUtil.cur().curUserId());
                insetDatabase(map,"cl_huju_type");
            }
            return jsonObject;

        }else if(StringUtils.equals(type, "3")){
            //删除
            if(StringUtils.isBlank(jsonObject.getString("id"))){
                return new Exception("未选中需要删除的护具");
            }
            //删除
            String batch = jsonObject.getString("batch");
            Map<String,Object> map = new HashMap<>();
            //单次删除
            if(StringUtils.equals(batch, "Y")){
                map.put("id",jsonObject.getString("id"));
                map.put("del_flag","1");
                return updateDatabase(map,"cl_huju_type");
            }
            //批量删除
            if(StringUtils.equals(batch, "N")){
                jsonObject.getJSONArray("id").forEach(item->{
                    map.put("id",item);
                    map.put("del_flag","1");
                    updateDatabase(map,"cl_huju_type");
                });
            }
            return batch;
        }
        return null;
    }
    /** 修改护具 */
    public int updateDatabase(Map<String, Object> param, String tableName) {
        List<String> fields = new ArrayList<>();
        param.forEach((k, v) -> {
            if (v != null && !"id".equals(k)) {
                fields.add(k + " = :" + k);
            }
        });
        String sql = String.format("UPDATE %s SET %s WHERE id = '%s'",
                tableName,
                String.join(", ", fields),
                param.get("id")
        );
        return jdbcTemplate.update(sql, param);
    }
    /** 修改护具 */
    public int insetDatabase(Map<String, Object> param, String tableName) {
        //封装新增的sql语句
        List<String> fields = new ArrayList<>();
        List<String> placeholders = new ArrayList<>();
        param.forEach((k, v) -> {
            if (v != null) {
                fields.add(k);
                placeholders.add(":" + k);
            }
        });

        String sql = String.format("INSERT INTO "+tableName+" (%s) VALUES (%s)",
                String.join(", ", fields),
                String.join(", ", placeholders)
        );
        int count = jdbcTemplate.update(sql, param);
        return count;
    }


}
